package com.lanxiao.cloud.modules.oauth.domain.check;

import com.lanxiao.cloud.common.core.enums.MethodEnum;
import com.lanxiao.cloud.common.core.exception.BusinessException;
import com.lanxiao.cloud.common.core.service.check.CheckHandle;
import com.lanxiao.cloud.modules.oauth.domain.model.Permission;
import com.lanxiao.cloud.modules.oauth.infrastructure.error.PermissionErrorType;
import java.util.List;
import java.util.Objects;

/**
 * @author ：qiaoliang
 * @date ：2021-09-15
 */
public class CheckPermissionHandle extends CheckHandle<Permission> {

  protected CheckPermissionHandle(Permission checkEntity) {
    super(checkEntity);
  }

  public static CheckPermissionHandle init(Permission permission) {
    return new CheckPermissionHandle(permission);
  }

  /**
   *  校验权限是否存在
   *
   * @author ：qiaoliang
   * @return com.lanxiao.cloud.modules.oauth.domain.check.CheckPermissionHandle
   * @date 2021-09-15 17:16
   */
  public CheckPermissionHandle checkExist() {
    BusinessException.isNull(checkEntity, PermissionErrorType.NO_PERMISSION_ERROR);
    return this;
  }

  /**
   *  校验标识是否重复
   *
   * @author ：qiaoliang
   * @param mark : 标识
   * @return com.lanxiao.cloud.modules.oauth.domain.check.CheckPermissionHandle
   * @date 2021-09-15 17:16
   */
  public CheckPermissionHandle checkRepeatMark(String mark) {
    BusinessException.isTrue(Objects.nonNull(checkEntity) && checkEntity.getMark().equals(mark),
        PermissionErrorType.MARK_REPEAT_ERROR);
    return this;
  }

  /**
   *  校验URL及请求类型是否重复
   *
   * @author ：qiaoliang
   * @param url : url
   * @param method : 类型
   * @return com.lanxiao.cloud.modules.oauth.domain.check.CheckPermissionHandle
   * @date 2021-09-15 17:16
   */
  public CheckPermissionHandle checkRepeatUrl(String url, MethodEnum method) {
    BusinessException.isTrue(Objects.nonNull(checkEntity) && checkEntity.getUrl().equals(url)
        && checkEntity.getMethod().equals(method),
        PermissionErrorType.URL_METHOD_REPEAT_ERROR);
    return this;
  }

  /**
   * 校验路由地址是否重复
   *
   * @author ：qiaoliang
   * @param path : 路由地址
   * @return com.lanxiao.cloud.modules.oauth.domain.check.CheckPermissionHandle
   * @date 2021-09-15 17:19
   */
  public CheckPermissionHandle checkRepeatPath(String path) {
    BusinessException.isTrue(Objects.nonNull(checkEntity) && checkEntity.getPath().equals(path),
        PermissionErrorType.PATH_REPEAT_ERROR);
    return this;
  }

  /**
   *  检查是否需要访问权限
   *
   * @author ：qiaoliang
   * @param list : 权限集合
   * @param url : 请求url
   * @param method : 请求类型
   * @return boolean
   * @date 2021-09-15 16:57
   */
  public static boolean checkNeedAccessPermission(List<Permission> list, String url, MethodEnum method) {
    for (Permission permission : list) {
      if (permission.isPermission(url, method)) {
        return Boolean.TRUE;
      }
    }
    return Boolean.FALSE;
  }

}
